package com.linktel.productionLine.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.github.pagehelper.PageInfo;
import com.linktel.productionLine.EasyExcel.CommentCellWriteHandler;
import com.linktel.productionLine.EasyExcel.util.Methods;
import com.linktel.productionLine.EasyExcel.dailyPlanning.DailyPlanningListener;
import com.linktel.productionLine.EasyExcel.dailyPlanning.model.WriteDailyPlanning;

import com.linktel.productionLine.common.BaseContext;
import com.linktel.productionLine.common.BaseResponse;
import com.linktel.productionLine.common.ErrorCode;
import com.linktel.productionLine.common.ResultUtils;
import com.linktel.productionLine.dao.BaseStepDao;
import com.linktel.productionLine.dao.DailyPlanningDao;
import com.linktel.productionLine.entity.dto.dailyPlanning.DailyPlanningDTO;
import com.linktel.productionLine.entity.query.dailyPlanning.*;
import com.linktel.productionLine.exception.BusinessException;
import com.linktel.productionLine.service.DailyPlanningService;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 对每日计划（日计划产能和排产）的相关请求
 *
 * @Author HuangJiaHui
 * @Date 2023/8/25 9:35
 */
@RestController
@RequestMapping("/daily-planning")
@AllArgsConstructor
public class DailyPlanningController {
    private DailyPlanningService dailyPanningService;
    private DailyPlanningDao dailyPlanningDao;
    private BaseStepDao baseStepDao;

    /**
     * 根据查询条件，返回日计划产能和排产列表
     *
     * @param listDailyPlanningQuery 用户id
     * @return 日计划产能和排产列表
     */
    @GetMapping
    public BaseResponse<PageInfo<DailyPlanningDTO>> listDailyPlanning(ListDailyPlanningQuery listDailyPlanningQuery) {
        if (listDailyPlanningQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        PageInfo<DailyPlanningDTO> dailyPlanningDTOList = dailyPanningService.listDailyPlanning(listDailyPlanningQuery);
        return ResultUtils.success(dailyPlanningDTOList);
    }

    /**
     * 新增产线的日计划产能和排产
     *
     * @param addDailyPlanningQuery 新增的产线的日计划产能和排产
     * @return 是否新增成功
     */
    @PostMapping
    public BaseResponse<Boolean> addDailyPlanning(@RequestBody AddDailyPlanningQuery addDailyPlanningQuery) {
        if (addDailyPlanningQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = dailyPanningService.addDailyPlanning(addDailyPlanningQuery);
        return ResultUtils.success(result);
    }

    /**
     * 修改产线的日计划产能和排产
     *
     * @param editDailyPlanningQuery 修改的日计划产能和排产
     * @return 是否修改成功
     */
    @PutMapping
    public BaseResponse<Boolean> editDailyPlanning(@RequestBody EditDailyPlanningQuery editDailyPlanningQuery) {
        if (editDailyPlanningQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = dailyPanningService.editDailyPlanning(editDailyPlanningQuery);
        return ResultUtils.success(result);
    }

    /**
     * 删除产线的日计划产能和排产
     *
     * @param deleteDailyPlanningQuery 删除的日计划产能和排产
     * @return 是否删除成功
     */
    @DeleteMapping
    public BaseResponse<Boolean> deleteDailyPlanning(@RequestBody DeleteDailyPlanningQuery deleteDailyPlanningQuery) {
        if (deleteDailyPlanningQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = dailyPanningService.deleteDailyPlanning(deleteDailyPlanningQuery);
        return ResultUtils.success(result);
    }



    /**
     * 下载通过excel批量保存的模板（只有表头，没有数据的excel文件）
     *
     * @param response
     */
    @GetMapping("/download/null")
    public void downloadNullDailyPlanningData(HttpServletResponse response) {

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 防止中文乱码
            String fileName = URLEncoder.encode("日计划产能和排产新增模板", "UTF-8")
                    .replaceAll("\\+","%20");
            response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ExcelTypeEnum.XLSX.getValue());
            //响应的输入流
            ServletOutputStream outputStream = response.getOutputStream();
            // workbook
            ExcelWriterBuilder writeWorkBook = EasyExcel.write(outputStream, WriteDailyPlanning.class).inMemory(Boolean.TRUE).inMemory(Boolean.TRUE)
                    .head(WriteDailyPlanning.class)
                    .useDefaultStyle(false)
                    .registerWriteHandler(new CommentCellWriteHandler(Methods.getNotationMap(WriteDailyPlanning.class)));// 添加备注的监听器

            // sheet
            writeWorkBook.sheet().sheetName("日计划产能和排产新增模板").sheetNo(0).doWrite(new ArrayList<>());
            outputStream.flush();
            outputStream.close();
        }catch (IOException | IllegalArgumentException e){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "导出失败");
        }
    }

    /**
     * 下载excel文件，内容包括筛选查询后的全部数据
     *
     * @param listDailyPlanningQuery 筛选查询出勤数据的封装对象
     */
    @GetMapping("/download")
    public void downloadDailyPlanningData(ListDailyPlanningQuery listDailyPlanningQuery, HttpServletResponse response) {
        if (listDailyPlanningQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<WriteDailyPlanning> writeDailyPlanning = dailyPanningService.downloadAttendanceDate(listDailyPlanningQuery);
        try {

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 防止中文乱码
            String fileName = URLEncoder.encode("日计划产能和排产", "UTF-8")
                    .replaceAll("\\+","%20");
            response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ExcelTypeEnum.XLSX.getValue());
            //响应的输入流
            ServletOutputStream outputStream = response.getOutputStream();
            // workbook
            ExcelWriterBuilder writeWorkBook = EasyExcel.write(outputStream, WriteDailyPlanning.class).inMemory(Boolean.TRUE)
                    .head(WriteDailyPlanning.class)
                    .useDefaultStyle(false)
                    .registerWriteHandler(new CommentCellWriteHandler(Methods.getNotationMap(WriteDailyPlanning.class)));// 添加备注的监听器

            // sheet
            writeWorkBook.sheet().sheetName("日计划产能和排产").sheetNo(0).doWrite(writeDailyPlanning);
            outputStream.flush();
            outputStream.close();


        }catch (IOException | IllegalArgumentException e){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "导出失败");
        }
    }
    /**
     * 上传excel文件，批量保存计划产能和排产
     *
     * @param file excel文件
     * @param currentUserId 当前用户Id
     * @return 是否插入成功
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@Param("file") MultipartFile file, Long currentUserId) {
        if (file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传数据为空");
        }
        try {
            EasyExcel.read(file.getInputStream(), WriteDailyPlanning.class, new DailyPlanningListener(dailyPlanningDao, currentUserId, baseStepDao)).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        String currentLog = BaseContext.getCurrentLog();
        return ResultUtils.success(currentLog);
    }
}
